<?php
/**
 * Video Model
 *
 * @author hiscaler <hiscaler@gmail.com>
 * @link http://www.yuandot.com/
 * @copyright Copyright &copy; 2009-2010 Yuandot Information Technology CO.,LTD.
 * @license http://doit.yuandot.com/license/
 */

class Video extends CActiveRecord {
    /**
     * The followings are the available columns in table '{{videos}}':
     * @var integer $id
     * @var integer $node_id
     * @var string $name
     * @var string $keywords
     * @var string $tags
     * @var string $summary
     * @var string $cover_saved_path
     * @var string $video_saved_path
     * @var integer $times_of_play_count
     * @var integer $order_pos
     * @var integer $status
     * @var integer $is_recommend
     * @var integer $is_picking
     * @var integer $created
     * @var integer $updated
     */

    public $times_of_play_count = 0;
    private $_oldTags;

    /**
     * Returns the static model of the specified AR class.
     * @return CActiveRecord the static model class
     */
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{videos}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
        return array(
            array('node_id, name, summary, order_pos, status', 'required'),
            array('node_id, times_of_play_count, order_pos, status, created, updated', 'numerical', 'integerOnly' => true),
            array('is_recommend, is_picking', 'boolean', 'falseValue' => 0, 'trueValue' => 1),
            array('name, cover_saved_path, keywords', 'length', 'max' => 200),
            array('video_saved_path', 'length', 'max' => 500),
            array('tags', 'length', 'max' => 400),
            array('tags', 'match', 'pattern'=>'/^[\x00-\xff,]+$/', 'message' => 'Tags can only contain word characters.'),
            array('tags', 'normalizeTags'),
            array('cover_saved_path', 'file', 'on' => 'hasCover',
                'allowEmpty' => false,
                'types' => 'jpg, jpeg, gif',
                'maxSize' => 1024 * 1024 * 10,
            ),
            array('video_saved_path', 'required', 'on' => 'isRequired'),
            array('video_saved_path', 'file', 'on' => 'isManualUploadMethod',
                'allowEmpty' => false,
                'types' => 'flv',
                'maxSize' => 1024 * 1024 * 10,
            ),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        return array(
            'node' => array(self::BELONGS_TO, 'Node', 'node_id'),
        );
    }



    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'Id',
            'node_id' => Yii::t('common', 'node_id'),
            'is_recommend' => Yii::t('common', 'is_recommend'),
            'is_picking' => Yii::t('common', 'is_picking'),
            'name' => Yii::t('video', 'name'),
            'keywords' => Yii::t('video', 'keywords'),
            'tags' => Yii::t('video', 'tags'),
            'summary' => Yii::t('video', 'summary'),
            'cover_saved_path' => Yii::t('video', 'cover_saved_path'),
            'video_saved_path' => Yii::t('video', 'video_saved_path'),
            'times_of_play_count' => Yii::t('video', 'times_of_play_count'),
            'order_pos' => Yii::t('common', 'order_pos'),
            'status' => Yii::t('video', 'status'),
            'created' => Yii::t('common', 'updated'),
            'updated' => Yii::t('common', 'updated'),
        );
    }

    /**
     * @return array a list of links that point to the post list filtered by every tag of this post
     */
    public function getTagLinks() {
        $links = array();
        foreach(Tag::string2array($this->tags) as $tag)
            $links[] = CHtml::link(CHtml::encode($tag), array('videos/index', 'tag' => $tag));
        return $links;
    }

    /**
     * Normalizes the user-entered tags.
     */
    public function normalizeTags($attribute, $params) {
        $this->tags = Tag::array2string(array_unique(Tag::string2array($this->tags)));
    }
    
    // "status" field Icon format
    public function getStatusIconFormat() {
        switch ($this->status) {
            case Options::STATUS_DRAFT:
                $img = 'status_draft.gif';
                break;
            case Options::STATUS_PUBLISHED:
                $img = 'status_published.gif';
                break;
            case Options::STATUS_PENDING_DELETE:
                $img = 'status_pending_delete.gif';
                break;
            default:
                $img = 'status_unknown.gif';
        }
        return CHtml::image(Yii::app()->assetManager->baseUrl . '/backend/images/' . $img);
    }

    // status AJax link
    public function getStatusAjaxLink() {
        return CHtml::ajaxLink($this->statusIconFormat,
            Yii::app()->createUrl('backend/videos/changeStatus'),
            array(
                'type' => 'POST',
                'data' => 'id=' . $this->id,
                'dataType' => 'text',
                'update' => "#status{$this->id}",
            ),
            array('id' => "status{$this->id}")
        );
    }

    // “是否推荐”图标格式
    public function getIsRecommendIconFormat() {
        $img = (intval($this->is_recommend) == Options::RECOMMEND_YES)
            ? 'yes.gif' : 'no.gif';
        return CHtml::image(Yii::app()->baseUrl . '/assets/backend/images/' . $img);
    }

    // change recommend status ajax link
    public function getIsRecommendAjaxLink() {
        return CHtml::ajaxLink($this->isRecommendIconFormat,
            Yii::app()->createUrl('backend/videos/changeRecommend'),
            array(
                'type' => 'POST',
                'data' => 'id=' . $this->id,
                'dataType' => 'text',
                'update' => "#recommend{$this->id}",
            ),
            array('id' => "recommend{$this->id}")
        );
    }

    // “是否精品”图标格式
    public function getIsPickingIconFormat() {
        $img = (intval($this->is_picking) == Options::PICKING_YES)
            ? 'yes.gif' : 'no.gif';
        return CHtml::image(Yii::app()->baseUrl . "/assets/backend/images/{$img}");
    }

    // change picking status ajax link
    public function getIsPickingAjaxLink() {
        return CHtml::ajaxLink($this->isPickingIconFormat,
            Yii::app()->createUrl('/backend/videos/changePicking'),
            array(
                'type' => 'POST',
                'data' => 'id=' . $this->id,
                'dataType' => 'text',
                'update' => "#picking{$this->id}",
            ),
            array('id' => "picking{$this->id}")
        );
    }

    // "updated" field formatted
    public function getUpdatedFormatted() {
        return ($this->updated) ? date('Y-m-d', $this->updated) : '';
    }

    public function behaviors() {
        return array(
            'CTimestampBehavior' => array(
                'class' => 'zii.behaviors.CTimestampBehavior',
                'createAttribute' => 'created',
                'updateAttribute' => 'updated',
            )
        );
    }

    // 视频封面地址
    public function getCoverPath() {
        return (!empty($this->cover_saved_path) || !is_null($this->cover_saved_path))
            ? Yii::app()->basePath . '/../upload/video/' . $this->cover_saved_path
            : '';
    }

    // 视频封面来源
    public function getCoverSource() {
        return (!empty($this->cover_saved_path) || !is_null($this->cover_saved_path))
            ? Yii::app()->baseUrl . '/upload/video/' . $this->cover_saved_path
            : '';
    }

    // 视频文件地址
    public function getVideoPath() {
        return Yii::app()->basePath . '/../upload/video/' . $this->video_saved_path;
//        return (empty($this->video_saved_path) || is_null($this->video_saved_path))
//            ? Yii::app()->basePath . '/../upload/video/' . $this->video_saved_path
//            : '';
    }

    // 视频文件来源
    public function getVideoSource() {
        $video_saved_path = $this->video_saved_path;
        $v = explode('.', $video_saved_path);
        if (count($v) != 2) { // 引用的视频路径直接返回
            return $video_saved_path;
        } else {
            Yii::app()->baseUrl . '/upload/video/' . $this->video_saved_path;
        }
    }

    /**
     * 判断上传文件采取的方式，是填写视频路径还是直接上传视频文件
     * 判断依据：
     * 　　文件是否含有"."，且分割之后数组个数为 2。小标为 2 的数组中值等于 'flv'，
     * 因为上传文件命名方式中除了扩展名的"."之外，再无其他其他"."标识。
     * @param <string> $value
     * @return boolean
     */
    private function checkIsManualUploadMethod($value) {
        $temps = explode('.', $value);
        if (count($temps) == 2) {
            if (isset($temps[1])) {
                return ($temps[1] == 'flv') ? true : false;
            }
        } else {
            return false;
        }
//        return (count($temps) != 2) ? false : true;
//        $pattern = '/^(http|https):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)/i';
//        return (is_string($value) && preg_match($pattern, $value))
//            ? false : true;
    }

    public function getIsManualUploadMethod() {
        return $this->checkIsManualUploadMethod($this->video_saved_path);
    }

    private $_original_picture_path;
    private $_original_video_path;
    protected function afterFind() {
        parent::afterFind();
        $this->_oldTags = $this->tags;
        $this->_original_picture_path = $this->cover_saved_path;
        $this->_original_video_path = $this->video_saved_path;
    }

    protected function beforeValidate() {
        parent::beforeValidate();

        // 设置是否上传视频封面场景
        $uploading_cover = CUploadedFile::getInstance($this, 'cover_saved_path');
        if (is_object($uploading_cover) && get_class($uploading_cover) === 'CUploadedFile') {
            $this->setScenario('hasCover');
        }

        $uploading_video = CUploadedFile::getInstance($this, 'video_saved_path');
        if (is_object($uploading_video) && get_class($uploading_video) === 'CUploadedFile') {
            $this->setScenario('isManualUploadMethod');
        } else {
            if ($this->isNewRecord) {
                // 如果是新上传视频文件，则一定需要提供，更新记录时则不需要
                $this->setScenario('isRequired');
            } else {
                $model = Video::model()->findByPk($this->id);
                // 如果以前采用的是手工填写地址的方式，则需要提供视频地
                if (!$model->IsManualUploadMethod) {
                    $this->setScenario('isRequired');
                }
            }
        }
        
        return true;
    }

    protected function beforeSave() {
        parent::beforeSave();

        // video cover uploading
        $uploading_cover = CUploadedFile::getInstance($this, 'cover_saved_path');
        if (is_object($uploading_cover) && get_class($uploading_cover) === 'CUploadedFile') {
            if (!$this->isNewRecord) {
                @unlink(Video::model()->findByPk($this->id)->coverPath);
            }
            $filename = md5(time() . $this->node_id) . '.' . $uploading_cover->getExtensionName();
            $this->cover_saved_path = $filename;
            $uploading_cover->saveAs(Yii::app()->basePath . '/../upload/video/' . $filename);
        } else {
            $this->cover_saved_path = $this->_original_picture_path;
        }

        // video file uploading
        $uploading_video = CUploadedFile::getInstance($this, 'video_saved_path');
        if (is_object($uploading_video) && get_class($uploading_video) === 'CUploadedFile') {
            if (!$this->isNewRecord) {
                @unlink(Video::model()->findByPk($this->id)->videoPath);
            }
            $filename = md5(time() . $this->node_id) . '.' . $uploading_video->getExtensionName();
            $this->video_saved_path = $filename;
            $uploading_video->saveAs(Yii::app()->basePath . '/../upload/video/' . $filename);
        } else {
//            $this->video_saved_path = $this->_original_video_path;
            // 如果原来是手动上传的视频文件，在修改时改成直接输入视频地址，则要删除原来上传的视频文件
            $model = Video::model()->findByPk($this->id);
            if ($model !== null) {
//                if ($model->isManualUploadMetho ($model->video_saved_path != trim($this->_original_video_path))) {
                if ($model->video_saved_path != trim($this->video_saved_path)) {
                    @unlink($model->videoPath);
                } else {
                    $this->video_saved_path = $this->_original_video_path;
                }
            }
        }

        return true;
    }

    protected function afterSave() {
        parent::afterSave();
        Tag::model()->updateFrequency($this->_oldTags, $this->tags, Tag::TYPE_VIDEO);
    }

    /**
     * 删除视频封面和视频文件
     */
    protected function afterDelete() {
        parent::afterDelete();
        Tag::model()->updateFrequency($this->tags, '', Tag::TYPE_VIDEO);
        if (!empty($this->cover_saved_path) || !is_null($this->cover_saved_path)) {
            @unlink($this->coverPath);
        }
        @unlink($this->videoPath);
    }

    protected function findBase($type = 'recent', $node = null, $limit = 12) {
        $criteria = new CDbCriteria();
        $criteria->condition = 'status = ' . Options::STATUS_PUBLISHED;
        if ($node !== null) {
            if (is_array($node)) {
                $criteria->addInCondition('node_id', $node);
            } else if (is_int($node)) {
                $criteria->addCondition("node_id = {$node}");
            }
        }
        switch ($type) {
            case 'recent':
                $criteria->order = 'created DESC';
                break;
            case 'hot':
                $criteria->order = 'times_of_play_count DESC';
                break;
            case 'recommend':
                $criteria->addCondition('is_recommend = ' . Options::RECOMMEND_YES);
                break;
            case 'picking':
                $criteria->addCondition('is_picking = ' . Options::PICKING_YES);
                break;
            default:
                $criteria->order = 'created DESC';
                break;
        }
        $criteria->limit = $limit;

        return self::model()->findAll($criteria);
    }

    // 最新信息
    public function findRecent($node = null, $limit = 12) {
        return $this->findBase('recent', $node, $limit);
    }

    // 热门信息
    public function findHot($node = null, $limit = 12) {
        return $this->findBase('hot', $node, $limit);
    }

    //　推荐信息
    public function findRecommend($node = null, $limit = 12) {
        return $this->findBase('recommend', $node, $limit);
    }

    // 置顶信息
    public function findPicking($node = null, $limit = 12) {
        return $this->findBase('picking', $node, $limit);
    }
}
